package controller

import (
	"ant-agent/exec/model"
	"ant-agent/exec/service"
	"ant-agent/pkg/logger"
	"ant-agent/pkg/response"

	"github.com/gin-gonic/gin"
)

func JobExec(c *gin.Context) {
	var task model.JobTask
	if err := c.ShouldBindJSON(&task); err != nil {
		response.Fail(c, nil, "参数错误")
		return
	}
	logger.Info("接收到作业执行请求: jobId=%s operation_type=%s usage_type=%s", task.Job.JobId, task.Job.OperationType, task.Job.UsageType)

	go func(job *model.JobTask) {
		if err := service.ExecJob(job); err != nil {
			logger.Error("任务执行失败: %s", err.Error())
		}
	}(&task)

	response.Success(c, nil, "任务已接受，正在执行")
}

func GetJobResult(c *gin.Context) {
	var jobParam struct {
		JobId string `json:"job_id"`
	}
	if err := c.ShouldBindJSON(&jobParam); err != nil {
		response.Fail(c, nil, "参数错误")
		return
	}

	result, err := service.GetJobStatus(jobParam.JobId)
	if err != nil {
		response.Fail(c, nil, "获取任务结果失败: "+err.Error())
		return
	}

	response.Success(c, result, "获取任务结果成功")
}

func ResumeManualJob(c *gin.Context) {
	var resumeReq model.TaskResumeRequest
	if err := c.ShouldBindJSON(&resumeReq); err != nil {
		response.Fail(c, nil, "参数错误")
		return
	}

	logger.Info("%+v", resumeReq)
	err := service.ResumeManualJob(&resumeReq)
	if err != nil {
		response.Fail(c, nil, err.Error())
		return
	}

	response.Success(c, nil, "成功")
}

// RetryJob 重试任务
func RetryJob(c *gin.Context) {
	var retryReq model.TaskRetryRequest
	if err := c.ShouldBindJSON(&retryReq); err != nil {
		response.Fail(c, nil, "参数错误: "+err.Error())
		return
	}

	logger.Debug("接收到任务重试请求: %+v", retryReq)

	go func(req *model.TaskRetryRequest) {
		if err := service.RetryJob(req); err != nil {
			logger.Error("任务重试失败: %s", err.Error())
		}
	}(&retryReq)

	response.Success(c, nil, "任务重试请求已接受")
}
